<template>
  <a-modal
    v-model="visible"
    title="编辑"
    @ok="onSubmit"
    @cancel="close"
  >
    <a-form-model
      v-if="visible"
      ref="cerForm"
      :model="form"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-model-item ref="nodeType" label="节点类型" v-if="currentNode.nodelevel===0">
        <a-switch checked-children="普通节点" un-checked-children="根节点" v-model="nodeTypeSelect"
                  @change="switchNodeType"></a-switch>
      </a-form-model-item>
      <a-form-model-item ref="nodeId" label="选择节点" prop="node.id">
        <a-select v-model="form.nodeId" placeholder="请选择节点">
          <a-select-option v-for="item in nodes" :key="item.id" :value="item.id">
            {{ item.nodename }}
          </a-select-option>
        </a-select>
      </a-form-model-item>

    </a-form-model>
  </a-modal>
</template>
<script>
import {createCer} from '@/api/nodeCertificate'
import {getAllNotHasCerNodes, getCurrentNode} from '@/api/node'
import {getRootAllNotHasCerNodes} from "@/api/rootnode";


export default {
  name: 'Edit',
  data: function () {
    return {
      labelCol: {span: 4},
      wrapperCol: {span: 14},
      other: '',
      visible: false,
      form: {
        id: '',
        node: {id: undefined}
      },
      nodes: [],
      currentNode: [],
      nodeType: 1,
      nodeTypeSelect: true,
      rules: {
        'nodeId': [
          {required: true, message: '请选择节点', trigger: 'blur'}
        ],
      },
    }
  },
  mounted() {
    getCurrentNode().then(res => this.currentNode = res.data).finally(() => console.log(this.currentNode))
  },
  methods: {
    switchNodeType(e) {
      this.getAllNodes()
    },
    getAllNodes() {
      const _this = this
      if (this.nodeTypeSelect) {
        getAllNotHasCerNodes().then(res => {
          _this.nodes = res.data
        })
      } else {
        getRootAllNotHasCerNodes().then(res => {
          _this.nodes = res.data
        })
      }
    },
    initData() {
      this.getAllNodes()
      this.visible = true
    },
    onSubmit() {
      this.$refs.cerForm.validate(valid => {
        if (valid) {
          if (this.nodeTypeSelect) {
            this.form.nodeType = 1
          } else {
            this.form.nodeType = 0
          }
          createCer(this.form).then(res => {
            if (res.code === '0') {
              this.$message.success('节点证书创建成功')
            } else {
              this.$message.error('节点证书创建失败')
            }
          }).finally(() => {
            this.close()
          })

        }
      })
    },
    close() {
      this.form = {
        id: '',
        node: {id: undefined}
      }
      this.visible = false
      this.$emit('ok')
    }
  }
}
</script>
